package com.mbigger.netty.ch7;

import com.mbigger.netty.ch2.handler.FirstClientHandler;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.oio.OioEventLoopGroup;
import io.netty.channel.rxtx.RxtxChannel;
import io.netty.channel.rxtx.RxtxChannelConfig;
import io.netty.channel.rxtx.RxtxDeviceAddress;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SerialMaster {

    public static final String PORT = "COM1";
    public static final Integer RATE = 9600;

    public static void main(String[] args) {
        EventLoopGroup workerGroup = new OioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workerGroup).channel(RxtxChannel.class).handler(new ChannelInitializer<RxtxChannel>() {
            @Override
            protected void initChannel(RxtxChannel ch) throws Exception {
                ch.config().setBaudrate(RATE).setParitybit(RxtxChannelConfig.Paritybit.NONE)
                        .setStopbits(RxtxChannelConfig.Stopbits.STOPBITS_1)
                        .setDatabits(RxtxChannelConfig.Databits.DATABITS_8).setWaitTimeMillis(0).setReadTimeout(1);
                ch.pipeline().addLast(new FirstClientHandler());
                log.info("通道初始化！");
            }
        });
        ChannelFuture channelFuture = bootstrap.connect(new RxtxDeviceAddress(PORT)).syncUninterruptibly();
        if (channelFuture != null && channelFuture.isSuccess()) {
            log.info("open seria[{}] successfully!", PORT);
        } else {
            log.error("open seria[{}] failure!", PORT);
        }
    }
}
